package com.gitee.fanx.retty.spring.springmvc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.fanx.retty.web.Request;
import com.gitee.fanx.retty.spring.ParamResolver;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ValueConstants;

import java.util.Objects;

/**
 * @author fanhang
 */
public abstract class AbstractParamResolver implements ParamResolver {
	private final String name;
	private final String defaultValue;
	private final boolean required;
	private final Class<?> clazz;
	private final ObjectMapper objectMapper;

	public AbstractParamResolver(String value, String name, String parameterName, String defaultValue, boolean required, Class<?> clazz, ObjectMapper objectMapper) {
		this.name = StringUtils.isAllBlank(value, name) ? parameterName : StringUtils.defaultIfBlank(value, name);
		this.defaultValue = defaultValue;
		this.required = required;
		this.clazz = clazz;
		this.objectMapper = objectMapper;
	}

	@Override
	public Object resolve(Request request) {
		String result = getValue(request, name);
		if (result == null) {
			result = defaultValue;
		}
		if (required && Objects.equals(ValueConstants.DEFAULT_NONE, result)) {
			throw new IllegalArgumentException("required argument [" + name + "] ");
		}
		if (result != null) {
			return objectMapper.convertValue(result, clazz);
		}
		return null;
	}

	/**
	 * 获取请求参数
	 * @param request 请求对象
	 * @param name 参数名
	 * @return 请求的参数值
	 */
	protected abstract String getValue(Request request, String name);

	protected String getName() {
		return name;
	}
}
